// LedDriver.cpp: implementation of the LedDriver class.
//
//////////////////////////////////////////////////////////////////////

#include "LedDriver.h"


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
 
LedDriver::LedDriver():LedDriver_base()
{
	pDev = NULL;
	isOn=false;
}

LedDriver::~LedDriver()
{
	if(pDev != NULL)
	{
		pDev->Close();
		delete pDev;
		pDev = NULL;
	}

}

int LedDriver::Init(char *pPortName)
{
	if(strcmp(pPortName,"NULL")==0)
	{
		pDev = NULL;
		return 1;
	}
	wxBaud baudrate = wxBAUD_38400;
	int timeout = 1000;

	if(pDev == NULL)	pDev = new wxSerialPort();
	if(pDev->Open(pPortName) < 0)
	{
		pDev = NULL;
		return -1;	
	}

	pDev->SetBaudRate(baudrate);

	Stop();
	Sleep(10);
	return 1;
}

int LedDriver::Start()
{
	char stica[20];
	memset(&stica[0],0,20);

	if (pDev == NULL) return 0;
	isOn=true;
	LED_Command CurrCommand;
	memset(&CurrCommand,0, sizeof(CurrCommand));
	
	CurrCommand.command = LEDS_ON;

	pDev->Write((char*)&CurrCommand,sizeof(CurrCommand));
	pDev->Read(stica, 20);
	return 1;
}

int LedDriver::Stop()
{
	char stica[20];
	memset(&stica[0],0,20);

	if (pDev == NULL) return 0;
	isOn=false;
	LED_Command CurrCommand;
	memset(&CurrCommand,0, sizeof(CurrCommand));
	
	CurrCommand.command = LEDS_OFF;

	pDev->Write((char*)&CurrCommand,sizeof(CurrCommand));
	pDev->Read(stica, 20);
	//cout<<"LED OFF"<<endl;

	return 1;
}

void LedDriver::Close()
{
	Stop();
}

int LedDriver::SetPeriods(int* pPeriods, char num)
{
	// 0 = left
	// 1 = right
	// 2 = up
	// 3 = down
	char stica[20];
	memset(&stica[0],0,20);

	if (pDev == NULL) return 0;

	int i;
	LED_Command CurrCommand;
	memset(&CurrCommand,0, sizeof(CurrCommand));
	if(num <=0 || num > 8) return -1;
	for(i=0; i<num;i++)
	{
		CurrCommand.Data[i] = pPeriods[i];
	
	}
	CurrCommand.command = SET_PERIODS;
	pDev->Write((char*)&CurrCommand,sizeof(CurrCommand));
	pDev->Read(stica, 20);
	//cout<<stica<<endl;
	if (isOn==true)
		Start();
	return i;
}